import React, { PureComponent } from 'react';
import { Icon, Form,Modal,Radio,Input,Tag,Tooltip,message} from 'antd';
import styles from './index.less';
import UploadFile from '../../../components/Upload/index';
message.config({
  top: 100,
  duration: 1.0,
});
const { TextArea } = Input;
const { CheckableTag } = Tag;
const FormItem = Form.Item;

const uploadButton = (
  <div>
    <Icon type="plus" />
    <div className="ant-upload-text">上传</div>
  </div>
);
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4},
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
    md: { span: 20 },
  },
};
const formImageItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4},
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
    md: { span: 20 },
  },
};
@Form.create()
class ShowForm extends PureComponent {
  state = {
    selectedTags: [],
    tags: [],
    tagValue:"",
    inputVisible: false,
    inputAddVisible: true,
    inputValue: '',
    radioValue:"0",

    reviewPerMissionsRadioValue:"0",
    attachTitle:"",
    attachURL:"",

    fileList: [],
    photoInfo:[],

    videoList: [],
    videoInfo:[]
  };


//标签部分
  saveInputRef = input => this.input = input;

  /**
   * 系统标签选择
   * @param tag
   * @param checked
   */
  handleTagChange(tag, checked) {
    const { selectedTags,tags,inputValue } = this.state;
    const nextSelectedTags = checked ?  [tag] : [];
    const tagValue = checked ? tag : "";
    this.setState({
      selectedTags: nextSelectedTags,
      tagValue:tagValue,
      tags: checked ? [] : tags,
      inputValue: checked ? "":inputValue,
      inputAddVisible: !checked
    });
  }

  /**
   * 删除自定义标签
   * @param removedTag
   */
  handleTagClose = (removedTag) => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    this.setState({
      tagValue:"",
      tags,
      inputAddVisible:true
    });
  }

  /**
   * 显示自定义标签输入的Input
   */
  showTagInput = () => {
    this.setState({
      inputVisible: true,
      inputAddVisible:false,
      },() => this.input.focus()
    );
  }
  /**
   * 自定义Tag修改的时候记录自定义tag值
   * @param e
   */
  handleTagInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }

  /**
   * 自定义标签input输入，点击Enter或者焦点离开
   */
  handleTagInputConfirm = () => {
    const state = this.state;
    const inputValue = state.inputValue;
    const tagValue = inputValue;
    let tags = state.tags;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }
    this.setState({
      tagValue:tagValue,
      tags,
      inputVisible: false,
      inputAddVisible: tagValue === "" ?  true:false,
      inputValue: '',
    });
  }

  handleAddInput = (e) => {
    this.setState({
      addInputValue: e.target.value,
    });
  }

  /**
   * 获取图片上传路径数组
   * @param imgSrc
   */
  getImageSrc = (imgSrc) => {
    this.setState({
      photoInfo:imgSrc
    });
  }
  /**
   * 获取视频上传路径数组
   * @param imgSrc
   */
  getVideoSrc= (videoSrc) => {
    this.setState({
      videoInfo:videoSrc
    });
  }
  /**
   * 生成链接DIV
   * @returns {XML}
   */
  renderAttachLianJie() {
    const { getFieldDecorator } = this.props.form;
    return  (
      <div>
        <FormItem
          {...formItemLayout}
          label="标题"
        >
          {getFieldDecorator('attachTitle', {
            rules: [{
              required: true, message: '请输入标题',
            }],
          })(
            <Input placeholder="请输入标题" onChange={this.handleAttachTitleInputChange} />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="链接地址"
        >
          {getFieldDecorator('attachURL', {
            rules: [{
              required: true, message: '请输入链接地址',
            }],
          })(
            <Input placeholder="请输入链接地址" onChange={this.handleAttachURLInputChange} />
          )}
        </FormItem>
      </div>
    )
  }

  /**
   * 生成照片DIV
   * @returns {XML}
   */
  renderAttachUploadImage () {
    const { fileList } = this.state;
    return (
      <FormItem
        {...formImageItemLayout}
        label=" "
        colon={false}
      >
          <UploadFile
          maxFileCount = {9}
          defaultList={fileList}
          getImgSrc={(imgSrc)=> this.getImageSrc(imgSrc)}
          buttonName = "照片上传"
          acceptName = 'image/*'
          suffixDefault = {['jpg']}
          data={{
          userId:1,
          filePath:'test/photo/'}}
          />
      </FormItem>
    )
  }

  /**
   * 生成视频DIV
   * @returns {XML}
   */
  renderAttachUploadVideo () {
    const {  videoList } = this.state;
    return (
      <FormItem
        {...formImageItemLayout}
        label=" "
        colon={false}
      >
        <UploadFile
          maxFileCount = {1}
          defaultList={videoList}
          getImgSrc={(videoSrc)=> this.getVideoSrc(videoSrc)}
          acceptName = "video/*"
          buttonName = "视屏上传"
          suffixDefault = {['mp4']}
          data={{
            userId:1,
            filePath:'test/photo/'}}
        />
      </FormItem>
    )
  }


  renderAttachByChoose() {
    if(this.state.radioValue == 1){
      return this.renderAttachLianJie() ;
    }else if(this.state.radioValue == 2){
      return this.renderAttachUploadImage();
    }else if(this.state.radioValue == 3) {
      return this.renderAttachUploadVideo();
    }
  }
  onRadioGroupChange = (e) => {
    this.setState({
      radioValue: e.target.value,
    });
  }


  /**
   * 审核权限
   * @param e
   */
  onReviewPerMissionsRadioGroupChange = (e) => {
    this.setState({
      reviewPerMissionsRadioValue: e.target.value,
    });
  }
  /**
   * 链接标题
   * @param e
   */
  handleAttachTitleInputChange = (e) => {
    this.setState({
      attachTitle: e.target.value,
    });
  }
  /**
   * 链接地址
   * @param e
   */
  handleAttachURLInputChange = (e) => {
    this.setState({
      attachURL: e.target.value,
    });
  }
  /**
   * 新增电台圈方法
   */
  handleAdd = () => {
    const { form } = this.props;
    var pbUserName = "";
    var showTxtContentInputValue = "";
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      pbUserName = fieldsValue.pbUserName && fieldsValue.pbUserName.valueOf();
      showTxtContentInputValue = fieldsValue.showTxtContent && fieldsValue.showTxtContent.valueOf();
    });
    const tagValue = this.state.tagValue; //标签值
    if(tagValue == null || tagValue == ""){
      message.info("请选择一个标签");
      return ;
    }
    const radioValue = this.state.radioValue;
    var showAttachment = [];
    if(radioValue == "0"){
      showAttachment = [];
    }else if(radioValue == "1"){
      showAttachment = [{"url":this.state.attachURL,"title":this.state.attachTitle}];
    }else if(radioValue == "2"){
      //照片处理
      const photoInfo = this.state.photoInfo;
      if(photoInfo.length <= 0){
        message.info("请上传图片");
        return ;
      }
      for(var index=0;index<photoInfo.length; index++){
        var imgSrc = {"url":photoInfo[index]};
        showAttachment.push(imgSrc);
      }
    }else if(radioValue == "3"){
      //视频处理
      const videoInfo = this.state.videoInfo;
      if(videoInfo.length <= 0){
        message.info("请上传视频");
        return ;
      }
      for(var index=0;index<videoInfo.length; index++){
        var videoSrc = {"src":videoInfo[index]};
        showAttachment.push(videoSrc);
      }
    }
    const reviewPerMissionsRadioValue = this.state.reviewPerMissionsRadioValue;
    const pbUserId = 1;   //此处需要根据实际登录用户修改
    this.props.handleAdd(tagValue,showTxtContentInputValue,radioValue,showAttachment,reviewPerMissionsRadioValue,pbUserName,pbUserId);
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedTags,tags, inputVisible, inputValue,inputAddVisible} = this.state;
    const {sysLable,modalVisible} = this.props;
    var tagsFromServer = [];
    for (var index = 0; index < sysLable.length; index++){
      var lableName = sysLable[index].lbName;
      tagsFromServer.push(lableName);
    }


    return (
      <Modal
        title="发布"
        visible={modalVisible}
        onOk={this.handleAdd}
        onCancel={() => this.props.handleModalVisible()}
        okText={"发布"}
      >
        <Form >
          <FormItem
            {...formItemLayout}
            label="标签"
          >
            {getFieldDecorator('sysTags')(
              <div>
                {tagsFromServer.map(tag => (
                  <CheckableTag
                    key={tag}
                    checked={selectedTags.indexOf(tag) > -1}
                    onChange={checked => this.handleTagChange(tag, checked)}
                  >
                    {tag}
                  </CheckableTag>
                ))}
              </div>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="自定义标签"
          >
            {getFieldDecorator('selfTags')(
              <div>
                {tags.map((tag, index) => {
                  const isLongTag = tag.length > 20;
                  const tagElem = (
                    <Tag key={tag} closable={true} afterClose={() => this.handleTagClose(tag)}>
                      {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                    </Tag>
                  );
                  return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
                })}
                {inputVisible && (
                  <Input
                    ref={this.saveInputRef}
                    type="text"
                    size="small"
                    style={{ width: 78 }}
                    value={inputValue}
                    onChange={this.handleTagInputChange}
                    onBlur={this.handleTagInputConfirm}
                    onPressEnter={this.handleTagInputConfirm}
                  />
                )}
                {inputAddVisible && (
                  <Tag
                    onClick={this.showTagInput}
                    style={{ background: '#fff', borderStyle: 'dashed' }}
                  >
                    <Icon type="plus" /> 新增标签
                  </Tag>
                )}
              </div>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="文字"
          >
            {getFieldDecorator('showTxtContent', {
              rules: [{
                required: true, message: '必填',
              }],
            })(
              <TextArea
                style={{ minHeight: 32 }}
                placeholder="必填"
                rows={4}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="附件"
          >
            {getFieldDecorator('attachType', {
              initialValue: "0",
            })(
              <Radio.Group onChange={this.onRadioGroupChange} >
                <Radio value="0">无</Radio>
                <Radio value="1">链接</Radio>
                <Radio value="2">照片</Radio>
                <Radio value="3">视频</Radio>
              </Radio.Group>
            )}
          </FormItem>
          {this.renderAttachByChoose()}
          <FormItem
            {...formItemLayout}
            label="评论权限"
          >
            {getFieldDecorator('showReviewPermissions', {
              initialValue:"0",
            })(
              <Radio.Group onChange={this.onReviewPerMissionsRadioGroupChange} >
                <Radio value="0">关闭评论功能</Radio>
                <Radio value="1">审核后显示</Radio>
                <Radio value="2">无需审核直接显示</Radio>
              </Radio.Group>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="发布人"
          >
            {getFieldDecorator('pbUserName', {
              initialValue:"张静",
              rules: [{
                required: true,
                message: '请输入发布人',
              }],
            })(
              <Input />
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

export default ShowForm;
